package com.woniuxy.controller;

import com.alibaba.fastjson2.JSON;
import com.woniuxy.entity.dto.stationPile.StationAddDTO;
import com.woniuxy.entity.dto.stationPile.StationInfoDTO;
import com.woniuxy.entity.po.stationPile.Station;
import com.woniuxy.entity.po.stationPile.StationSchedule;
import com.woniuxy.service.StationService;
import com.woniuxy.util.MinioUtils;
import com.woniuxy.util.PageParam;
import com.woniuxy.util.ResponseData;
import lombok.AllArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@RestController
@AllArgsConstructor
@RequestMapping("/station")
public class StationController {
    private StationService stationService;
    private MinioUtils minioUtils;

    @PostMapping("/queryAll")
    public ResponseData<?> queryAll(@RequestBody PageParam<?> pageParam) {
        return ResponseData.ok(stationService.queryAll(pageParam));
    }

    @PostMapping("/queryInfo")
    public ResponseData<?> queryInfo(@RequestBody PageParam<StationInfoDTO> pageParam) {
        return ResponseData.ok(stationService.queryInfo(pageParam));
    }

    @GetMapping("/del/{id}")
    public ResponseData<?> del(@PathVariable Long id) {
        stationService.del(id);
        return ResponseData.ok();
    }

    @PostMapping("/batchDel")
    public ResponseData<?> batchDel(@RequestBody List<Long> ids) {
        stationService.batchDel(ids);
        return ResponseData.ok();
    }

    @GetMapping("/queryAllForMap")
    public ResponseData<?> queryAllForMap() {
        return ResponseData.ok(stationService.queryAllForMap());
    }

    @GetMapping("/queryStationTypeList")
    public ResponseData<?> queryStationTypeList() {
        return ResponseData.ok(stationService.queryStationTypeList());
    }

    /**
     * 查询充电站详情，包含图片、充电桩和收费规则
     *
     * @param id 充电站ID
     * @return 详情数据
     */
    @GetMapping("/queryBasicInfo/{id}")
    public ResponseData<?> queryBasicInfo(@PathVariable Long id) {
        return ResponseData.ok(stationService.queryBasicInfo(id));
    }

    @PostMapping("/add")
    @Transactional
    public ResponseData<?> addStation(StationAddDTO StationAddDTO,
                                      @RequestPart(value = "schedules", required = false) String schedulesJson,
                                      @RequestPart(value = "imgSrc", required = false) List<MultipartFile> imgFiles
    ) {
        List<StationSchedule> schedules = JSON.parseArray(schedulesJson, StationSchedule.class);
        Station station = new Station(StationAddDTO);
        station.setSchedules(schedules);
        StationMinIOUploadAndAddImgSrc(imgFiles, station);
        stationService.addStation(station);
        return ResponseData.ok();
    }

    private void StationMinIOUploadAndAddImgSrc(List<MultipartFile> imgFiles, Station station) {
        if (imgFiles == null || imgFiles.isEmpty()) {
            return;
        }
        
        // 先确保imgSrc列表已初始化
        if (station.getImgSrc() == null) {
            station.setImgSrc(new ArrayList<>());
        }
        
        for (MultipartFile imgFile : imgFiles) {
            try {
                String imgUrl = minioUtils.uploadFile(imgFile);
                if (imgUrl != null) {
                    station.getImgSrc().add(imgUrl);
                }
            } catch (Exception e) {
                e.printStackTrace();
                // 考虑添加日志或抛出自定义异常
            }
        }
    }
    @PostMapping("/update")
    @Transactional
    public ResponseData<?> updateStation(
            StationAddDTO stationAddDTO,
            @RequestPart(value = "schedules", required = false) String schedulesJson,
            @RequestPart(value = "imgSrc", required = false) List<MultipartFile> newImages,
            @RequestPart(value = "existingImgUrls", required = false) String existingImgUrlsStr
    ) {
        List<StationSchedule> schedules = JSON.parseArray(schedulesJson, StationSchedule.class);
        List<String> existingUrls = StringUtils.hasText(existingImgUrlsStr)
                ? Arrays.asList(existingImgUrlsStr.split(","))
                : Collections.emptyList();

        Station station = new Station(stationAddDTO);
        station.setSchedules(schedules);

        stationService.updateStation(station, newImages, existingUrls);
        return ResponseData.ok();
    }

}
